package example;

import org.junit.Test;

import java.io.RandomAccessFile;

/**
 * 支持随机访问
 * 既能输入也能输出
 * 任意位置插入 读取
 * RandomAccessFile(String name, String mode)
 RandomAccessFile(File file, String mode)
 mode:  r 只读方式打开
 rw 打开以读取和写入
 rwd 打开以读取和写入 同步文件内容的更新
 rws 打开以读取和写入 同步文件内容和元数据的更新
 */
public class RandomAccessFileTest {

    @Test
    public void readwrite() {
        
        try(
            RandomAccessFile readFile = new RandomAccessFile("1.txt", "r");
            RandomAccessFile writeFile = new RandomAccessFile("2.txt", "rw")
        ) {
            byte[] bytes = new byte[10];
            int len = 0;
            while (true) {
                len = readFile.read(bytes);
                if (len == -1) {
                    break;
                }
                writeFile.write(bytes, 0, len);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
  
    }







    @Test
    public  void testRandom() {
        
        try(
                RandomAccessFile randomAccessFile = new RandomAccessFile("r.txt", "rw")
        ) {
            
            randomAccessFile.seek(50);

            randomAccessFile.write('A');
            randomAccessFile.write('B');
            randomAccessFile.write('C');
            long pointer = randomAccessFile.getFilePointer();
            System.out.println(pointer);
            randomAccessFile.seek(0);
            String str = randomAccessFile.readLine();
            System.out.println(str);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}




